package controllers;

import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import util.DAO;
import util.Entity;

public class ModelsCtrl extends Controller {

	@Transactional
	public static Result persist(String nameOfModel) throws Exception {
		Class<? extends Entity> c = Entity.getClass(nameOfModel);
		Entity o = Json.fromJson(request().body().asJson(), c);
		DAO.persist(o);
		return ok(o.getId().toString());
	}

	@Transactional(readOnly = true)
	public static Result find(String nameOfModel, Long id) throws Exception {
		Class<? extends Entity> c = Entity.getClass(nameOfModel);
		return ok(Json.toJson(DAO.find(c, id)));
	}

	@Transactional(readOnly = true)
	public static Result navigate(String nameOfModel, Long id,
			String nameOfAttribute) throws Exception {
		Class<? extends Entity> c = Entity.getClass(nameOfModel);

		Entity entity = DAO.find(c, id);
		Object res = entity.get(nameOfAttribute);

		return ok(Json.toJson(res));

		// FIXME Avoid going twice to DB
	}
}
